package com.icoolkj.ms.auth.feign;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.icoolkj.ms.api.auth.bo.UserInfoInTokenBO;
import com.icoolkj.ms.api.auth.dto.AccountRegisterDTO;
import com.icoolkj.ms.common.core.enums.UserTypeEnum;
import com.icoolkj.ms.api.auth.feign.AccountRegisterFeignClient;
import com.icoolkj.ms.api.auth.model.AuthAccount;
import com.icoolkj.ms.api.auth.vo.AuthAccountVO;
import com.icoolkj.ms.api.auth.vo.TokenInfoVO;
import com.icoolkj.ms.auth.manager.TokenManager;
import com.icoolkj.ms.auth.service.IAuthAccountService;
import com.icoolkj.ms.common.core.exception.IcoolkjMSException;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import com.icoolkj.ms.common.core.utils.BeanUtil;
import com.icoolkj.ms.common.core.utils.uuid.IdWorker;
import com.icoolkj.ms.common.security.enums.InputUserNameEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/19 10:59
 */
@RestController
public class AccountRegisterFeignController implements AccountRegisterFeignClient {

    @Autowired
    private IAuthAccountService iAuthAccountService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TokenManager tokenManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Long> saveUserRegister(AccountRegisterDTO accountRegisterDTO) {
        AuthAccount authAccount = BeanUtil.map(accountRegisterDTO, AuthAccount.class);
        this.checkRegisterInfo(authAccount);
        if (StrUtil.isNotBlank(authAccount.getPassword())) {
            authAccount.setPassword(passwordEncoder.encode(authAccount.getPassword()));
        }
        authAccount.setUid(IdWorker.nextId());
        iAuthAccountService.saveAuthAccount(authAccount);

        return ServerResponseEntity.success(authAccount.getUid());
    }


    @Override
    public ServerResponseEntity<TokenInfoVO> storeTokenAndGetVo(UserInfoInTokenBO userInfoInTokenBO) {
        return ServerResponseEntity.success(tokenManager.storeAndGetVo(userInfoInTokenBO));
    }

    private void checkRegisterInfo(AuthAccount authAccount) {
        // 检查用户名是否已存在
        if (StrUtil.isNotEmpty(authAccount.getUserName())) {
            checkFieldExistence("用户名", authAccount.getUserName(), UserTypeEnum.NORMAL_USER.getCode());
        }
        // 检查手机号是否已存在
        if (StrUtil.isNotEmpty(authAccount.getPhoneNumber())) {
            checkFieldExistence("手机号", authAccount.getPhoneNumber(), UserTypeEnum.NORMAL_USER.getCode());
        }
        // 检查邮箱是否已存在
        if (StrUtil.isNotEmpty(authAccount.getEmail())) {
            checkFieldExistence("邮箱", authAccount.getEmail(), UserTypeEnum.NORMAL_USER.getCode());
        }

    }

    private void checkFieldExistence(String fieldName, String fieldValue, String userType) {
        if (fieldValue != null && !fieldValue.isEmpty()) {
            ServerResponseEntity<AuthAccountVO> responseEntity = null;
            switch (fieldName) {
                case "用户名":
                    responseEntity = iAuthAccountService.getByInputUsernameAndUserType(InputUserNameEnum.USERNAME.value(), fieldValue, userType);
                    break;
                case "手机号":
                    responseEntity = iAuthAccountService.getByInputUsernameAndUserType(InputUserNameEnum.PHONE.value(), fieldValue, userType);
                    break;
                case "邮箱":
                    responseEntity = iAuthAccountService.getByInputUsernameAndUserType(InputUserNameEnum.EMAIL.value(), fieldValue, userType);
                    break;
            }
            if (!responseEntity.isSuccess()) {
                throw new IcoolkjMSException(responseEntity.getMessage());
            }
            if (ObjectUtil.isNotEmpty(responseEntity.getData())) {
                throw new IcoolkjMSException(fieldName + "已存在");
            }
        }
    }

}
